/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.sumgr.core;

import io.iec.edp.caf.sumgr.api.ServiceUnitGenerator;
import io.iec.edp.caf.sumgr.api.entity.ServiceUnitInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author wangyandong
 * @date 2021/04/09 10:11
 *
 */
@Deprecated
public class ServiceUnitGeneratorImpl implements ServiceUnitGenerator {
    private static final String FILE_NAME="ServiceUnit.json";
    private static final String JSON_FORMAT=
            "{\n" +
            "    \"ServiceUnitInfo\" :\n" +
            "    {\n" +
            "        \"ApplicationName\" : \"%s\",\n" +
            "        \"ServiceUnitName\" : \"%s\",\n" +
            "        \"Type\" : \"%s\"\n" +
            "    }\n" +
            "}";
    private static final Logger logger = LoggerFactory.getLogger(ServiceUnitGeneratorImpl.class);

    /**
     * whether ServiceUnit.json exists
     * @param destDir   The directory for the root of the package hierarchy
     *                          for generated files.
     */
    public Boolean exists(File destDir){
        if(destDir==null || destDir.isDirectory()==false)
            throw new IllegalArgumentException("destDir is null or invalidate");

        File[] files = destDir.listFiles((dir, name) -> {
            File file1 = new File(dir, name);
            return file1.isFile() && name != null && "ServiceUnit.json".equalsIgnoreCase(name);
        });

        //识别为su目录
        return  (files != null && files.length > 0);
    }


    /**
     * Generate ServiceUnit.json.
     * @param destDir   The directory for the root of the package hierarchy
     *                          for generated files. Can not be null.
     */
    @Override
    public void generate(ServiceUnitInfo info, File destDir) {
        if(info==null || info.getName()==null || info.getApplicationName()==null)
            throw new IllegalArgumentException("ServiceUnitInfo is null or contains empty parameter");

        if(destDir==null || destDir.isDirectory()==false)
            throw new IllegalArgumentException("destDir is null or invalidate");

        File file = new File(destDir,FILE_NAME);
        if (file.exists()) {
            return;
        }
        try {
            //创建文件
            file.createNewFile();

            String suType = StringUtils.isEmpty(info.getType())? "Biz":info.getType();
            String data = String.format(JSON_FORMAT, info.getApplicationName(), info.getName(), suType);
            try (FileWriter fileWritter = new FileWriter(file, true);
                 BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
            ) {
                bufferWritter.write(data);
                bufferWritter.flush();
            }
        }catch(IOException e) {
            logger.error(e.getMessage(),e);
        }
    }
}
